// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.FBAInvoice;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryExchangeVo;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.FBAInvoiceDetailMapper;
import com.fowo.api.mapper.FBAInvoiceLogisticsMapper;
import com.fowo.api.mapper.FBAInvoiceMapper;
import com.fowo.api.mapper.LogisticsChannelMapper;
import com.fowo.api.mapper.LogisticsProviderMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.fbainvoice.FBAInvoiceAllocateInventoryAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceExcelPo;
import com.fowo.api.model.fbainvoice.FBAInvoiceFinishPickingAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceImportPo;
import com.fowo.api.model.fbainvoice.FBAInvoiceItemVo;
import com.fowo.api.model.fbainvoice.FBAInvoiceLockinventoryAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceMarkLockedAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceMarkasshippedAction;
import com.fowo.api.model.fbainvoice.FBAInvoicePushStockOutAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceReleaseInventoryAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceSearchParamPo;
import com.fowo.api.model.fbainvoice.FBAInvoiceShippingAction;
import com.fowo.api.model.fbainvoice.FBAInvoiceVo;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceGeneraltradingEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceInsureEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceIsPickEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceIslockinventoryEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceModeoftransportEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoicePrintStatusEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceReceivingmethodEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceTaxgrossupEnums;
import com.fowo.api.model.fbainvoice.constant.FBAInvoiceTransportModeEnums;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVo;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVoPages;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailSearchParamPo;
import com.fowo.api.model.fbainvoice.logistics.FBAInvoiceLogisticsSearchParamPo;
import com.fowo.api.model.logistics.channel.LogisticsChannelItemVo;
import com.fowo.api.model.logistics.channel.LogisticsChannelSearchParamPo;
import com.fowo.api.model.logistics.provider.LogisticsProviderItemVo;
import com.fowo.api.model.logistics.provider.LogisticsProviderSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.FBAInvoiceDetailService;
import com.fowo.api.service.FBAInvoiceLogisticsService;
import com.fowo.api.service.FBAInvoiceService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发货单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：袁江，吕家傲
 */
@Slf4j
@DataObjectType(FBAInvoice.class)
@DS("ds24")
public class FBAInvoiceBaseServiceImpl
  extends ServiceImpl<FBAInvoiceMapper, FBAInvoice>
  implements FBAInvoiceService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("deliveryWarehouseName", "w.`name`");
      put("logisticsprovider1Name", "lp.`name`");
      put("logisticsChannel1Name", "lc.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected FBAInvoiceService self;

  @Resource
  protected FBAInvoiceDetailService fBAInvoiceDetailService;

  @Resource
  protected FBAInvoiceLogisticsService fBAInvoiceLogisticsService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected LogisticsProviderMapper logisticsProviderMapper;

  @Resource
  protected LogisticsChannelMapper logisticsChannelMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected FBAInvoiceMarkLockedAction fBAInvoiceMarkLockedAction;

  @Autowired(required = false)
  protected FBAInvoiceReleaseInventoryAction fBAInvoiceReleaseInventoryAction;

  @Autowired(required = false)
  protected FBAInvoiceLockinventoryAction fBAInvoiceLockinventoryAction;

  @Autowired(required = false)
  protected FBAInvoicePushStockOutAction fBAInvoicePushStockOutAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected FBAInvoiceFinishPickingAction fBAInvoiceFinishPickingAction;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected FBAInvoiceShippingAction fBAInvoiceShippingAction;

  @Autowired(required = false)
  protected FBAInvoiceAllocateInventoryAction fBAInvoiceAllocateInventoryAction;

  @Autowired(required = false)
  protected FBAInvoiceMarkasshippedAction fBAInvoiceMarkasshippedAction;

  @Resource
  protected Validator validator;

  /**
   * 创建发货单
   * @param model 发货单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FBAInvoiceVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInvoice entity = new FBAInvoice();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getTransportMode() == null) {
      entity.setTransportMode("1");
    }

    if (model.getPaymentStatus() == null) {
      entity.setPaymentStatus("50");
    }

    if (model.getInvoiceStatus() == null) {
      entity.setInvoiceStatus("10");
    }

    if (model.getPrintStatus() == null) {
      entity.setPrintStatus("0");
    }

    if (model.getIsPick() == null) {
      entity.setIsPick("0");
    }

    if (model.getLogisticsExpectedAging() == null) {
      entity.setLogisticsExpectedAging(0);
    }

    if (model.getAllocationType() == null) {
      entity.setAllocationType("10");
    }

    if (model.getIsOut() == null) {
      entity.setIsOut(false);
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getInoviceCode())) {
      entity.setInoviceCode(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "FBAInvoice.inoviceCode")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("发货单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 发货单
   */
  protected void updateAllChilds(FBAInvoiceVo model) throws Exception {
    if (model.getInvoiceDetailList() != null) {
      fBAInvoiceDetailService.saveAllByParentFBAInvoice(
        model.getId(),
        model.getInvoiceDetailList()
      );
    }

    if (model.getLogisticsinfo() != null) {
      fBAInvoiceLogisticsService.saveAllByParentFBAInvoice(
        model.getId(),
        model.getLogisticsinfo()
      );
    }
  }

  /**
   * 更新发货单
   * @param model 发货单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FBAInvoiceVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInvoice entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "logisticsCenterCode"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新发货单（带空值）
   * @param model 发货单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FBAInvoiceVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInvoice entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(FBAInvoice::getDeliveryWarehouse, model.getDeliveryWarehouse())
      .set(FBAInvoice::getLastUpdateTime, model.getLastUpdateTime())
      .set(FBAInvoice::getLastUpdateUser, model.getLastUpdateUser())
      .set(FBAInvoice::getSendTime, model.getSendTime())
      .set(FBAInvoice::getRemark, model.getRemark())
      .set(FBAInvoice::getFile, model.getFile())
      .set(FBAInvoice::getNetWeight, model.getNetWeight())
      .set(FBAInvoice::getGrossWeight, model.getGrossWeight())
      .set(FBAInvoice::getTotalVolume, model.getTotalVolume())
      .eq(FBAInvoice::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FBAInvoiceSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 发货单详情(invoiceDetailList) 对应的对象
    FBAInvoiceDetailSearchParamPo invoiceDetailListSearchParam =
      new FBAInvoiceDetailSearchParamPo();
    invoiceDetailListSearchParam.setDisableDataPremissions(true);
    invoiceDetailListSearchParam.setParentFBAInvoiceInList(ids);
    FBAInvoiceDetailMapper localFBAInvoiceDetailMapper = ContextHolder
      .getApplicationContext()
      .getBean(FBAInvoiceDetailMapper.class);
    invoiceDetailListSearchParam.applySqlSegments();
    List<Long> invoiceDetailListIdList = localFBAInvoiceDetailMapper.searchIds(
      invoiceDetailListSearchParam
    );
    if (!invoiceDetailListIdList.isEmpty()) {
      FBAInvoiceDetailService localFBAInvoiceDetailService = ContextHolder
        .getApplicationContext()
        .getBean(FBAInvoiceDetailService.class);
      localFBAInvoiceDetailService.batchDelete(invoiceDetailListIdList);
    }

    // 处理子表字段 物流信息(logisticsinfo) 对应的对象
    FBAInvoiceLogisticsSearchParamPo logisticsinfoSearchParam =
      new FBAInvoiceLogisticsSearchParamPo();
    logisticsinfoSearchParam.setDisableDataPremissions(true);
    logisticsinfoSearchParam.setParentFBAInvoiceInList(ids);
    FBAInvoiceLogisticsMapper localFBAInvoiceLogisticsMapper = ContextHolder
      .getApplicationContext()
      .getBean(FBAInvoiceLogisticsMapper.class);
    logisticsinfoSearchParam.applySqlSegments();
    List<Long> logisticsinfoIdList = localFBAInvoiceLogisticsMapper.searchIds(
      logisticsinfoSearchParam
    );
    if (!logisticsinfoIdList.isEmpty()) {
      FBAInvoiceLogisticsService localFBAInvoiceLogisticsService = ContextHolder
        .getApplicationContext()
        .getBean(FBAInvoiceLogisticsService.class);
      localFBAInvoiceLogisticsService.batchDelete(logisticsinfoIdList);
    }
  }

  /**
   * 删除发货单
   * @param id 发货单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除发货单
   * @param ids 发货单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<FBAInvoiceImportPo> excelToImportRow(
    FBAInvoiceImportPo row,
    Integer rowNumber,
    FBAInvoiceVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<FBAInvoiceImportPo> ir = new ImportRow<FBAInvoiceImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<FBAInvoiceImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new FBAInvoiceVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, FBAInvoiceImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getTransportMode())) {
      vo.setTransportMode(
        FBAInvoiceTransportModeEnums.toValue(row.getTransportMode())
      );
      if (vo.getTransportMode() == null) {
        ir.addError(
          "transportMode",
          "运输方式只能是：“快递”, “海运”, “空运”, “其他”"
        );
      }
    }
    vo.setSendTime(SheetUtils.tryToDateTime(row.getSendTime()));
    vo.setExpectReachTime(SheetUtils.tryToDateTime(row.getExpectReachTime()));
    vo.setRealitySendTime(SheetUtils.tryToDateTime(row.getRealitySendTime()));
    if (StringUtils.hasText(row.getPaymentStatus())) {
      List<SysDictAllItem> paymentStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "paymentStatus",
          n -> sysDictService.getDictItems("SCM00071")
        );
      FBAInvoiceVo finalVo = vo;
      paymentStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPaymentStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPaymentStatus(i.getItemValue()),
          () ->
            ir.addError(
              "paymentStatus",
              String.format(
                "必须为 %s 中之一",
                paymentStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getInvoiceStatus())) {
      List<SysDictAllItem> invoiceStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "invoiceStatus",
          n -> sysDictService.getDictItems("SCM00072")
        );
      FBAInvoiceVo finalVo = vo;
      invoiceStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getInvoiceStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setInvoiceStatus(i.getItemValue()),
          () ->
            ir.addError(
              "invoiceStatus",
              String.format(
                "必须为 %s 中之一",
                invoiceStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPrintStatus())) {
      vo.setPrintStatus(
        FBAInvoicePrintStatusEnums.toValue(row.getPrintStatus())
      );
      if (vo.getPrintStatus() == null) {
        ir.addError("printStatus", "打印状态只能是：“未打印”, “已打印”");
      }
    }
    vo.setPrintNum(SheetUtils.tryToInteger(row.getPrintNum()));
    if (StringUtils.hasText(row.getIsPick())) {
      vo.setIsPick(FBAInvoiceIsPickEnums.toValue(row.getIsPick()));
      if (vo.getIsPick() == null) {
        ir.addError("isPick", "拣货状态只能是：“未拣货”, “已拣货”");
      }
    }
    vo.setPickTime(SheetUtils.tryToDateTime(row.getPickTime()));
    vo.setShipmentPlanTime(SheetUtils.tryToDateTime(row.getShipmentPlanTime()));
    vo.setLogisticsExpectedAging(
      SheetUtils.tryToInteger(row.getLogisticsExpectedAging())
    );
    if (StringUtils.hasText(row.getAllocationType())) {
      List<SysDictAllItem> allocationTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "allocationType",
          n -> sysDictService.getDictItems("SCM00077")
        );
      FBAInvoiceVo finalVo = vo;
      allocationTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getAllocationType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setAllocationType(i.getItemValue()),
          () ->
            ir.addError(
              "allocationType",
              String.format(
                "必须为 %s 中之一",
                allocationTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setIsOut(SheetUtils.tryToBoolean(row.getIsOut()));
    if (StringUtils.hasText(row.getIslockinventory())) {
      vo.setIslockinventory(
        FBAInvoiceIslockinventoryEnums.toValue(row.getIslockinventory())
      );
      if (vo.getIslockinventory() == null) {
        ir.addError("islockinventory", "是否锁库存只能是：“是”, “否”");
      }
    }
    if (StringUtils.hasText(row.getModeoftransport())) {
      vo.setModeoftransport(
        FBAInvoiceModeoftransportEnums.toValue(row.getModeoftransport())
      );
      if (vo.getModeoftransport() == null) {
        ir.addError("modeoftransport", "运输方式只能是：“海派”, “空派”");
      }
    }
    if (StringUtils.hasText(row.getReceivingmethod())) {
      vo.setReceivingmethod(
        FBAInvoiceReceivingmethodEnums.toValue(row.getReceivingmethod())
      );
      if (vo.getReceivingmethod() == null) {
        ir.addError(
          "receivingmethod",
          "收件方式只能是：“上门揽收”, “送货上门”"
        );
      }
    }
    vo.setCollectiontime(SheetUtils.tryToDate(row.getCollectiontime()));
    SheetUtils.datePreviewFormat(
      row.getCollectiontime(),
      row::setCollectiontime
    );
    if (StringUtils.hasText(row.getGeneraltrading())) {
      vo.setGeneraltrading(
        FBAInvoiceGeneraltradingEnums.toValue(row.getGeneraltrading())
      );
      if (vo.getGeneraltrading() == null) {
        ir.addError("generaltrading", "一般贸易只能是：“是”, “否”");
      }
    }
    if (StringUtils.hasText(row.getTaxgrossup())) {
      vo.setTaxgrossup(FBAInvoiceTaxgrossupEnums.toValue(row.getTaxgrossup()));
      if (vo.getTaxgrossup() == null) {
        ir.addError("taxgrossup", "包税只能是：“是”, “否”");
      }
    }
    if (StringUtils.hasText(row.getInsure())) {
      vo.setInsure(FBAInvoiceInsureEnums.toValue(row.getInsure()));
      if (vo.getInsure() == null) {
        ir.addError("insure", "保险只能是：“是”, “否”");
      }
    }
    vo.setShipmentIds(SheetUtils.tryToLong(row.getShipmentIds()));
    vo.setNetWeight(SheetUtils.tryToDecimal(row.getNetWeight()));
    vo.setGrossWeight(SheetUtils.tryToDecimal(row.getGrossWeight()));
    vo.setTotalVolume(SheetUtils.tryToDecimal(row.getTotalVolume()));
    // 处理关联字段“发货仓库”
    if (
      !SheetUtils.isBlank(row.getDeliveryWarehouseName()) &&
      SheetUtils.isBlank(row.getDeliveryWarehouse())
    ) {
      WarehouseSearchParamPo deliveryWarehouseSearchParam =
        new WarehouseSearchParamPo();
      deliveryWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getDeliveryWarehouseName())
      );
      deliveryWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> deliveryWarehouseMatches = warehouseMapper.search(
        deliveryWarehouseSearchParam
      );
      if (deliveryWarehouseMatches.size() == 0) {
        ir.addError(
          "deliveryWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (deliveryWarehouseMatches.size() > 1) {
        ir.addError(
          "deliveryWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryWarehouse(deliveryWarehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流商”
    if (
      !SheetUtils.isBlank(row.getLogisticsprovider1Name()) &&
      SheetUtils.isBlank(row.getLogisticsprovider1())
    ) {
      LogisticsProviderSearchParamPo logisticsprovider1SearchParam =
        new LogisticsProviderSearchParamPo();
      logisticsprovider1SearchParam.setLimit(2); // 最大只返回二行记录
      logisticsprovider1SearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsprovider1Name())
      );
      logisticsprovider1SearchParam.applySqlSegments();
      List<LogisticsProviderItemVo> logisticsprovider1Matches =
        logisticsProviderMapper.search(logisticsprovider1SearchParam);
      if (logisticsprovider1Matches.size() == 0) {
        ir.addError("logisticsprovider1Name", "未能在物流商中找到匹配的数据");
      } else if (logisticsprovider1Matches.size() > 1) {
        ir.addError(
          "logisticsprovider1Name",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsprovider1(logisticsprovider1Matches.get(0).getId());
      }
    }
    // 处理关联字段“物流渠道”
    if (
      !SheetUtils.isBlank(row.getLogisticsChannel1Name()) &&
      SheetUtils.isBlank(row.getLogisticsChannel1())
    ) {
      LogisticsChannelSearchParamPo logisticsChannel1SearchParam =
        new LogisticsChannelSearchParamPo();
      logisticsChannel1SearchParam.setLimit(2); // 最大只返回二行记录
      logisticsChannel1SearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsChannel1Name())
      );
      logisticsChannel1SearchParam.applySqlSegments();
      List<LogisticsChannelItemVo> logisticsChannel1Matches =
        logisticsChannelMapper.search(logisticsChannel1SearchParam);
      if (logisticsChannel1Matches.size() == 0) {
        ir.addError("logisticsChannel1Name", "未能在物流渠道中找到匹配的数据");
      } else if (logisticsChannel1Matches.size() > 1) {
        ir.addError(
          "logisticsChannel1Name",
          "关联不唯一，在物流渠道中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsChannel1(logisticsChannel1Matches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<FBAInvoiceImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<FBAInvoiceImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            FBAInvoiceImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(FBAInvoiceImportPo row, AnalysisContext cxt) {
              FBAInvoiceVo vo = new FBAInvoiceVo();
              ImportRow<FBAInvoiceImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<FBAInvoiceImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<FBAInvoiceImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      FBAInvoiceVo vo = new FBAInvoiceVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"发货单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "inoviceCode".equals(m.getField())
          )
      ) {
        vo.setInoviceCode(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "FBAInvoice.inoviceCode")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    FBAInvoiceSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "deliveryWarehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FBAInvoiceItemVo) r).getDeliveryWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "transportMode",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            FBAInvoiceTransportModeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "invoiceStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00072")
      );
      exportOptions.addFieldMappingOption(
        "printStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> FBAInvoicePrintStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "isPick",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> FBAInvoiceIsPickEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "islockinventory",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            FBAInvoiceIslockinventoryEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsprovider1",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FBAInvoiceItemVo) r).getLogisticsprovider1Name())
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsChannel1",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FBAInvoiceItemVo) r).getLogisticsChannel1Name())
          )
      );
      exportOptions.addStringFields(
        "inoviceCode",
        "deliveryWarehouseName",
        "shipmentCode",
        "transportMode",
        "sendName",
        "invoiceStatus",
        "printStatus",
        "isPick",
        "lxCreateUser",
        "remark",
        "islockinventory",
        "productitems",
        "planSendQuantity",
        "declarationQuantity",
        "sendQuantity",
        "logisticsprovider1Name",
        "logisticsChannel1Name"
      );

      String fileName = String.format(
        "发货单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> invoiceStatusItems = sysDictService.getDictItems(
      "SCM00072"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<FBAInvoiceExcelPo> items = new ArrayList<FBAInvoiceExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<FBAInvoiceItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<FBAInvoiceItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (FBAInvoiceItemVo item : list) {
        FBAInvoiceExcelPo excel = new FBAInvoiceExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setTransportMode(
          FBAInvoiceTransportModeEnums.toLabel(item.getTransportMode())
        );
        if (item.getInvoiceStatus() != null) {
          invoiceStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getInvoiceStatus()))
            .findFirst()
            .ifPresent(i -> excel.setInvoiceStatus(i.getItemText()));
        }
        excel.setPrintStatus(
          FBAInvoicePrintStatusEnums.toLabel(item.getPrintStatus())
        );
        excel.setIsPick(FBAInvoiceIsPickEnums.toLabel(item.getIsPick()));
        excel.setIslockinventory(
          FBAInvoiceIslockinventoryEnums.toLabel(item.getIslockinventory())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "发货单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(FBAInvoiceExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过物流商查询发货单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByLogisticsProvider(String logisticsProvider) {
    return this.baseMapper.getIdByLogisticsProvider(logisticsProvider);
  }

  /**
   * 通过物流商查询发货单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByLogisticsProvider(List<String> list) {
    return this.baseMapper.getIdsByLogisticsProvider(list);
  }

  /**
   * 通过发货单主键查询物流商
   */
  @Override
  public String getLogisticsProviderById(Long id) {
    return this.baseMapper.getLogisticsProviderById(id);
  }

  /**
   * 通过发货单主键查询物流商列表
   */
  @Override
  public List<String> getLogisticsProviderByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getLogisticsProviderByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("logisticsProvider")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 发货单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public FBAInvoiceVo getVoById(Long id) throws Exception {
    FBAInvoiceVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    FBAInvoiceDetailSearchParamPo invoiceDetailListSearchParamPo =
      new FBAInvoiceDetailSearchParamPo();
    invoiceDetailListSearchParamPo.setParentFBAInvoice(id);
    invoiceDetailListSearchParamPo.getExtendData().put("queryMode", "sub");
    invoiceDetailListSearchParamPo
      .getExtendData()
      .put("queryParent", "FBAInvoice");
    invoiceDetailListSearchParamPo.applySqlSegments();
    vo.setInvoiceDetailList(
      fBAInvoiceDetailService.search(invoiceDetailListSearchParamPo)
    );

    FBAInvoiceLogisticsSearchParamPo logisticsinfoSearchParamPo =
      new FBAInvoiceLogisticsSearchParamPo();
    logisticsinfoSearchParamPo.setParentFBAInvoice(id);
    logisticsinfoSearchParamPo.getExtendData().put("queryMode", "sub");
    logisticsinfoSearchParamPo.getExtendData().put("queryParent", "FBAInvoice");
    logisticsinfoSearchParamPo.applySqlSegments();
    vo.setLogisticsinfo(
      fBAInvoiceLogisticsService.search(logisticsinfoSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询发货单
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<FBAInvoiceItemVo> pageSearch(FBAInvoiceSearchParamPo search) {
    Page<FBAInvoiceItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FBAInvoiceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<FBAInvoiceItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<FBAInvoiceItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    FBAInvoiceDetailSearchParamPo invoiceDetailListSearchParamPo =
      new FBAInvoiceDetailSearchParamPo();
    invoiceDetailListSearchParamPo.setSort(sort);
    invoiceDetailListSearchParamPo.setPageSize(200);
    invoiceDetailListSearchParamPo.setParentFBAInvoiceInList(
      pageResult
        .getRecords()
        .stream()
        .map(FBAInvoiceItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<FBAInvoiceDetailItemVoPages>> invoiceDetailListMaps =
      fBAInvoiceDetailService.pagesByParentFBAInvoice(
        invoiceDetailListSearchParamPo
      );

    for (FBAInvoiceItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "invoiceDetailList",
        invoiceDetailListMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(FBAInvoiceSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("invoiceDetailList")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    FBAInvoiceSearchParamPo search
  ) {
    FBAInvoiceSearchParamPo parentSearchParam = new FBAInvoiceSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<FBAInvoiceItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      FBAInvoiceItemVo itemVo = parentList.get(0);

      FBAInvoiceDetailSearchParamPo invoiceDetailListSearchParamPo =
        new FBAInvoiceDetailSearchParamPo();
      invoiceDetailListSearchParamPo.setPageSize(search.getPageSize());
      invoiceDetailListSearchParamPo.setCurrent(search.getCurrent());
      invoiceDetailListSearchParamPo.setParentFBAInvoice(itemVo.getId());
      return fBAInvoiceDetailService.pageSearch(invoiceDetailListSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 发货单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FBAInvoiceOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FBAInvoiceItemVo>> searchOptions(
    FBAInvoiceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询发货单
   * @param search 查询条件
   * @return 发货单列表查询结果
   */
  @Override
  public List<FBAInvoiceItemVo> search(FBAInvoiceSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询发货单最后更新时间
   * @param search 查询条件
   * @return 发货单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FBAInvoiceSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 作废
   */
  /**
   * 标记已锁库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了标记已锁库操作"
  )
  @Override
  public void markLocked(List<Long> ids) throws Exception {
    if (fBAInvoiceMarkLockedAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceMarkLockedAction.run(ids);
  }

  /**
   * 释放库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放库存操作"
  )
  @Override
  public void releaseInventory(List<Long> ids) throws Exception {
    if (fBAInvoiceReleaseInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceReleaseInventoryAction.run(ids);
  }

  /**
   * 锁库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存操作"
  )
  @Override
  public void lockinventory(List<Long> ids) throws Exception {
    if (fBAInvoiceLockinventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceLockinventoryAction.run(ids);
  }

  /**
   * 推送出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了推送出库单操作"
  )
  @Override
  public void pushStockOut(List<Long> ids) throws Exception {
    if (fBAInvoicePushStockOutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoicePushStockOutAction.run(ids);
  }

  /**
   * 同步数据
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步数据操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void syncData() throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/FBAInvoice_syncData.js",
      null,
      null,
      this
    );
  }

  /**
   * 完成拣货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了完成拣货操作"
  )
  @Override
  public void finishPicking(List<Long> ids) throws Exception {
    if (fBAInvoiceFinishPickingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceFinishPickingAction.run(ids);
  }

  /**
   * 拣货即时库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了拣货即时库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void finishPickingInventory(List<Long> ids) throws Exception {
    List<Long> list = Convert.toList(Long.class, ids);
    for (Long id : list) {
      FBAInvoiceVo vo = getVoById(id);
      InventoryExchangeFormVo formVo = prepareFinishPickingInventory(vo);
      inventoryBusinessService.exchange(formVo);
      // 更新成功状态
      FBAInvoice updateStatusEntity = new FBAInvoice();
      updateStatusEntity.setId(id);
      updateStatusEntity.setIsPick("1");
      updateById(updateStatusEntity);
    }
  }

  /**
   * 准备用于 拣货即时库存 的参数
   */
  protected InventoryExchangeFormVo prepareFinishPickingInventory(
    FBAInvoiceVo vo
  ) throws Exception {
    if (!"0".equals(vo.getIsPick())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Picking);
    formVo.setFormNum(vo.getId().toString());
    formVo.setDocumentType("fba拣货流转库存");
    if (ObjectUtils.isEmpty(vo.getLxCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLxCreateUser());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliveryWarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShopId()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShopId())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getFnsku() == null
              ? null
              : fBAInvoiceDetail.getFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 拣货仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了拣货仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void finishPickingBingId(List<Long> ids) throws Exception {
    List<Long> list = Convert.toList(Long.class, ids);
    for (Long id : list) {
      FBAInvoiceVo vo = getVoById(id);
      InventoryExchangeFormVo formVo = prepareFinishPickingBingId(vo);
      inventoryBusinessService.exchange(formVo);
      // 更新成功状态
      FBAInvoice updateStatusEntity = new FBAInvoice();
      updateStatusEntity.setId(id);
      updateStatusEntity.setIsPick("1");
      updateById(updateStatusEntity);
    }
  }

  /**
   * 准备用于 拣货仓位 的参数
   */
  protected InventoryExchangeFormVo prepareFinishPickingBingId(FBAInvoiceVo vo)
    throws Exception {
    if (!"0".equals(vo.getIsPick())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getId().toString());
    formVo.setDocumentType("fba拣货流转仓位");
    if (ObjectUtils.isEmpty(vo.getLxCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLxCreateUser());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliveryWarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShopId()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShopId())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getFnsku() == null
              ? null
              : fBAInvoiceDetail.getFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        fBAInvoiceDetail.getOutBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        fBAInvoiceDetail.getInBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 发货出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了发货出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void shippingOut(List<Long> ids) throws Exception {
    List<Long> list = Convert.toList(Long.class, ids);
    for (Long id : list) {
      FBAInvoiceVo vo = getVoById(id);
      InventoryOutboundFormVo formVo = prepareShippingOut(vo);
      inventoryBusinessService.outbound(formVo);
      // 更新成功状态
      FBAInvoice updateStatusEntity = new FBAInvoice();
      updateStatusEntity.setId(id);
      updateStatusEntity.setInvoiceStatus("40");
      updateById(updateStatusEntity);
    }
  }

  /**
   * 准备用于 发货出库 的参数
   */
  protected InventoryOutboundFormVo prepareShippingOut(FBAInvoiceVo vo)
    throws Exception {
    if (!"30".equals(vo.getInvoiceStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Picking);
    formVo.setFormNum(vo.getInoviceCode());
    formVo.setDocumentType("fba发货");
    if (ObjectUtils.isEmpty(vo.getSendName())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getSendName());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      outboundItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShopId()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShopId())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getFnsku() == null
              ? null
              : fBAInvoiceDetail.getFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        fBAInvoiceDetail.getInBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 发货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了发货操作"
  )
  @Override
  public void shipping(List<Long> ids) throws Exception {
    if (fBAInvoiceShippingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceShippingAction.run(ids);
  }

  /**
   * 分配库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了分配库存操作"
  )
  @Override
  public void allocateInventory(List<Long> ids) throws Exception {
    if (fBAInvoiceAllocateInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceAllocateInventoryAction.run(ids);
  }

  /**
   * 标记已发货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了标记已发货操作"
  )
  @Override
  public void markasshipped(List<Long> ids) throws Exception {
    if (fBAInvoiceMarkasshippedAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInvoiceMarkasshippedAction.run(ids);
  }

  /**
   * 锁库存_即时
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_即时操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void locksInventory(Long id) throws Exception {
    FBAInvoiceVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLocksInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    FBAInvoice updateStatusEntity = new FBAInvoice();
    updateStatusEntity.setId(id);
    updateStatusEntity.setInvoiceStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_即时 的参数
   */
  protected InventoryExchangeFormVo prepareLocksInventory(FBAInvoiceVo vo)
    throws Exception {
    if (!"30".equals(vo.getInvoiceStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getInoviceCode());
    formVo.setDocumentType("发货单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliveryWarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShipmentShop()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getShipmentShopFnsku() == null
              ? null
              : fBAInvoiceDetail.getShipmentShopFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShopFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 锁库存_仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockpInventory(Long id) throws Exception {
    FBAInvoiceVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockpInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    FBAInvoice updateStatusEntity = new FBAInvoice();
    updateStatusEntity.setId(id);
    updateStatusEntity.setInvoiceStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_仓位 的参数
   */
  protected InventoryExchangeFormVo prepareLockpInventory(FBAInvoiceVo vo)
    throws Exception {
    if (!"30".equals(vo.getInvoiceStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getInoviceCode());
    formVo.setDocumentType("发货单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliveryWarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShipmentShop()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getShipmentShopFnsku() == null
              ? null
              : fBAInvoiceDetail.getShipmentShopFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShopFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        fBAInvoiceDetail.getOutBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        fBAInvoiceDetail.getOutBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 取消锁库存_即时
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消锁库存_即时操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelLocksInventory(Long id) throws Exception {
    FBAInvoiceVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareCancelLocksInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    FBAInvoice updateStatusEntity = new FBAInvoice();
    updateStatusEntity.setId(id);
    updateStatusEntity.setInvoiceStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消锁库存_即时 的参数
   */
  protected InventoryExchangeFormVo prepareCancelLocksInventory(
    FBAInvoiceVo vo
  ) throws Exception {
    if (!"30".equals(vo.getInvoiceStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getInoviceCode());
    formVo.setDocumentType("取消发货单锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliveryWarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShipmentShop()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getShipmentShopFnsku() == null
              ? null
              : fBAInvoiceDetail.getShipmentShopFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShopFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 取消锁库存_仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消锁库存_仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelLockpInventory(Long id) throws Exception {
    FBAInvoiceVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareCancelLockpInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    FBAInvoice updateStatusEntity = new FBAInvoice();
    updateStatusEntity.setId(id);
    updateStatusEntity.setInvoiceStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消锁库存_仓位 的参数
   */
  protected InventoryExchangeFormVo prepareCancelLockpInventory(
    FBAInvoiceVo vo
  ) throws Exception {
    if (!"30".equals(vo.getInvoiceStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getInoviceCode());
    formVo.setDocumentType("取消发货锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliveryWarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      exchangeItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShipmentShop()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getShipmentShopFnsku() == null
              ? null
              : fBAInvoiceDetail.getShipmentShopFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShopFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        fBAInvoiceDetail.getOutBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        fBAInvoiceDetail.getOutBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 出库锁定
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库锁定操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockStockOut(Long id) throws Exception {
    FBAInvoiceVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareLockStockOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    FBAInvoice updateStatusEntity = new FBAInvoice();
    updateStatusEntity.setId(id);
    updateStatusEntity.setInvoiceStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 出库锁定 的参数
   */
  protected InventoryOutboundFormVo prepareLockStockOut(FBAInvoiceVo vo)
    throws Exception {
    if (!"30".equals(vo.getInvoiceStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(FBAInvoiceVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getInoviceCode());
    formVo.setDocumentType("发货单");
    if (ObjectUtils.isEmpty(vo.getLxCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getLxCreateUser());
    if (ObjectUtils.isEmpty(vo.getDeliveryWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getDeliveryWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (FBAInvoiceDetailItemVo fBAInvoiceDetail : vo.getInvoiceDetailList()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(fBAInvoiceDetail.getName());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(fBAInvoiceDetail.getSendQuantity())
      );
      outboundItem.setShopId(
        String.valueOf(fBAInvoiceDetail.getShipmentShop()).equals("null")
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShop())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            fBAInvoiceDetail.getShipmentShopFnsku() == null
              ? null
              : fBAInvoiceDetail.getShipmentShopFnsku().trim()
          )
          ? null
          : String.valueOf(fBAInvoiceDetail.getShipmentShopFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        fBAInvoiceDetail.getOutBingId(),
        Integer.parseInt(
          String.valueOf(fBAInvoiceDetail.getSendQuantity()).equals("null")
            ? "0"
            : String.valueOf(fBAInvoiceDetail.getSendQuantity())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Lock);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(fBAInvoiceDetail.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    FBAInvoiceSearchParamPo search = new FBAInvoiceSearchParamPo();
    return MapUtil
      .builder()
      .put("FBAInvoiceAllView", this.baseMapper.fBAInvoiceAllViewCount(search))
      .put(
        "FBAInvoiceDistributedView",
        this.baseMapper.fBAInvoiceDistributedViewCount(search)
      )
      .put(
        "FBAInvoiceSendView",
        this.baseMapper.fBAInvoiceSendViewCount(search)
      )
      .put(
        "FBAInvoiceHasSendView",
        this.baseMapper.fBAInvoiceHasSendViewCount(search)
      )
      .put(
        "FBAInvoiceCancelView",
        this.baseMapper.fBAInvoiceCancelViewCount(search)
      )
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<FBAInvoiceItemVo> fBAInvoiceAllView(
    FBAInvoiceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.fBAInvoiceAllView(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<FBAInvoiceItemVo> fBAInvoiceAllViewPage(
    FBAInvoiceSearchParamPo search
  ) {
    Page<FBAInvoiceItemVo> fBAInvoiceAllViewPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return fBAInvoiceAllViewPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return fBAInvoiceAllViewPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    fBAInvoiceAllViewPage =
      this.baseMapper.fBAInvoiceAllViewPage(
          search.toPage(this.baseMapper.fBAInvoiceAllViewCount(search)),
          search
        );
    List<Long> recordIds = fBAInvoiceAllViewPage
      .getRecords()
      .stream()
      .map(FBAInvoiceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return fBAInvoiceAllViewPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return fBAInvoiceAllViewPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    fBAInvoiceAllViewPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return fBAInvoiceAllViewPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<?> fBAInvoiceAllViewPageWithChildSearch(
    FBAInvoiceSearchParamPo search
  ) {
    return appendWithChild(
      fBAInvoiceAllViewPage(search),
      search.toChildSort("invoiceDetailList")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date fBAInvoiceAllViewLastUpdateTime(FBAInvoiceSearchParamPo search) {
    return this.baseMapper.fBAInvoiceAllViewLastUpdateTime(search);
  }

  /**
   * 待配货
   */
  @Override
  public List<FBAInvoiceItemVo> fBAInvoiceDistributedView(
    FBAInvoiceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.fBAInvoiceDistributedView(search);
  }

  /**
   * 待配货分页
   */
  @Override
  public Page<FBAInvoiceItemVo> fBAInvoiceDistributedViewPage(
    FBAInvoiceSearchParamPo search
  ) {
    Page<FBAInvoiceItemVo> fBAInvoiceDistributedViewPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return fBAInvoiceDistributedViewPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return fBAInvoiceDistributedViewPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    fBAInvoiceDistributedViewPage =
      this.baseMapper.fBAInvoiceDistributedViewPage(
          search.toPage(this.baseMapper.fBAInvoiceDistributedViewCount(search)),
          search
        );
    List<Long> recordIds = fBAInvoiceDistributedViewPage
      .getRecords()
      .stream()
      .map(FBAInvoiceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return fBAInvoiceDistributedViewPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return fBAInvoiceDistributedViewPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    fBAInvoiceDistributedViewPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return fBAInvoiceDistributedViewPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<?> fBAInvoiceDistributedViewPageWithChildSearch(
    FBAInvoiceSearchParamPo search
  ) {
    return appendWithChild(
      fBAInvoiceDistributedViewPage(search),
      search.toChildSort("invoiceDetailList")
    );
  }

  /**
   * 查询待配货最后更新时间
   * @param search 查询条件
   * @return 待配货最后更新时间
   */
  @Override
  public Date fBAInvoiceDistributedViewLastUpdateTime(
    FBAInvoiceSearchParamPo search
  ) {
    return this.baseMapper.fBAInvoiceDistributedViewLastUpdateTime(search);
  }

  /**
   * 待发货
   */
  @Override
  public List<FBAInvoiceItemVo> fBAInvoiceSendView(
    FBAInvoiceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.fBAInvoiceSendView(search);
  }

  /**
   * 待发货分页
   */
  @Override
  public Page<FBAInvoiceItemVo> fBAInvoiceSendViewPage(
    FBAInvoiceSearchParamPo search
  ) {
    Page<FBAInvoiceItemVo> fBAInvoiceSendViewPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return fBAInvoiceSendViewPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return fBAInvoiceSendViewPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    fBAInvoiceSendViewPage =
      this.baseMapper.fBAInvoiceSendViewPage(
          search.toPage(this.baseMapper.fBAInvoiceSendViewCount(search)),
          search
        );
    List<Long> recordIds = fBAInvoiceSendViewPage
      .getRecords()
      .stream()
      .map(FBAInvoiceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return fBAInvoiceSendViewPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return fBAInvoiceSendViewPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    fBAInvoiceSendViewPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return fBAInvoiceSendViewPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<?> fBAInvoiceSendViewPageWithChildSearch(
    FBAInvoiceSearchParamPo search
  ) {
    return appendWithChild(
      fBAInvoiceSendViewPage(search),
      search.toChildSort("invoiceDetailList")
    );
  }

  /**
   * 查询待发货最后更新时间
   * @param search 查询条件
   * @return 待发货最后更新时间
   */
  @Override
  public Date fBAInvoiceSendViewLastUpdateTime(FBAInvoiceSearchParamPo search) {
    return this.baseMapper.fBAInvoiceSendViewLastUpdateTime(search);
  }

  /**
   * 已发货
   */
  @Override
  public List<FBAInvoiceItemVo> fBAInvoiceHasSendView(
    FBAInvoiceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.fBAInvoiceHasSendView(search);
  }

  /**
   * 已发货分页
   */
  @Override
  public Page<FBAInvoiceItemVo> fBAInvoiceHasSendViewPage(
    FBAInvoiceSearchParamPo search
  ) {
    Page<FBAInvoiceItemVo> fBAInvoiceHasSendViewPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return fBAInvoiceHasSendViewPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return fBAInvoiceHasSendViewPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    fBAInvoiceHasSendViewPage =
      this.baseMapper.fBAInvoiceHasSendViewPage(
          search.toPage(this.baseMapper.fBAInvoiceHasSendViewCount(search)),
          search
        );
    List<Long> recordIds = fBAInvoiceHasSendViewPage
      .getRecords()
      .stream()
      .map(FBAInvoiceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return fBAInvoiceHasSendViewPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return fBAInvoiceHasSendViewPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    fBAInvoiceHasSendViewPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return fBAInvoiceHasSendViewPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<?> fBAInvoiceHasSendViewPageWithChildSearch(
    FBAInvoiceSearchParamPo search
  ) {
    return appendWithChild(
      fBAInvoiceHasSendViewPage(search),
      search.toChildSort("invoiceDetailList")
    );
  }

  /**
   * 查询已发货最后更新时间
   * @param search 查询条件
   * @return 已发货最后更新时间
   */
  @Override
  public Date fBAInvoiceHasSendViewLastUpdateTime(
    FBAInvoiceSearchParamPo search
  ) {
    return this.baseMapper.fBAInvoiceHasSendViewLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<FBAInvoiceItemVo> fBAInvoiceCancelView(
    FBAInvoiceSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.fBAInvoiceCancelView(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<FBAInvoiceItemVo> fBAInvoiceCancelViewPage(
    FBAInvoiceSearchParamPo search
  ) {
    Page<FBAInvoiceItemVo> fBAInvoiceCancelViewPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return fBAInvoiceCancelViewPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return fBAInvoiceCancelViewPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    fBAInvoiceCancelViewPage =
      this.baseMapper.fBAInvoiceCancelViewPage(
          search.toPage(this.baseMapper.fBAInvoiceCancelViewCount(search)),
          search
        );
    List<Long> recordIds = fBAInvoiceCancelViewPage
      .getRecords()
      .stream()
      .map(FBAInvoiceItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return fBAInvoiceCancelViewPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return fBAInvoiceCancelViewPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    fBAInvoiceCancelViewPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return fBAInvoiceCancelViewPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货单分页查询结果
   */
  @Override
  public Page<?> fBAInvoiceCancelViewPageWithChildSearch(
    FBAInvoiceSearchParamPo search
  ) {
    return appendWithChild(
      fBAInvoiceCancelViewPage(search),
      search.toChildSort("invoiceDetailList")
    );
  }

  /**
   * 查询已作废最后更新时间
   * @param search 查询条件
   * @return 已作废最后更新时间
   */
  @Override
  public Date fBAInvoiceCancelViewLastUpdateTime(
    FBAInvoiceSearchParamPo search
  ) {
    return this.baseMapper.fBAInvoiceCancelViewLastUpdateTime(search);
  }
}
